package cn.org.eshow.service.impl;

import cn.org.eshow.bean.query.OrderItemQuery;
import cn.org.eshow.bean.query.AdditionalOrderQuery;
import cn.org.eshow.common.ShopDataVar;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.component.getui.GetuiUtil;
import cn.org.eshow.component.pingpay.config.PingConfig;
import cn.org.eshow.dao.AdditionalOrderDao;
import cn.org.eshow.model.*;
import cn.org.eshow.service.*;
import cn.org.eshow.util.OrderUtil;
import cn.org.eshow.util.StringUtil;
import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Refund;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import cn.org.eshow.service.MoneyManager;

@WebService(serviceName = "AdditionalOrderService", endpointInterface = "cn.org.eshow.service.AdditionalOrderManager")
@Service
public class AdditionalOrderManagerImpl extends GenericManagerImpl<AdditionalOrder, Integer> implements AdditionalOrderManager {

    @Autowired
    AdditionalOrderDao additionalOrderDao;
    @Autowired
    OrderStepManager orderStepManager;
    @Autowired
    BillManager billManager;
    @Autowired
    ProductOrderManager productOrderManager;
    @Autowired
    NotificationManager notificationManager;
    @Autowired
    FinanceManager financeManager;
    @Autowired
    MoneyManager moneyManager;

    public AdditionalOrderManagerImpl() {
    }

    @Autowired
    public AdditionalOrderManagerImpl(AdditionalOrderDao additionalOrderDao) {
        super(additionalOrderDao);
        this.additionalOrderDao = additionalOrderDao;
    }

    @Override
    public List<AdditionalOrder> list(AdditionalOrderQuery query) {
        return additionalOrderDao.list(query);
    }

    @Override
    public Page<AdditionalOrder> search(AdditionalOrderQuery query) {
        return additionalOrderDao.search(query);
    }

    @Override
    public AdditionalOrder check(AdditionalOrderQuery query) {
        List<AdditionalOrder> list = additionalOrderDao.list(query);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Integer count(AdditionalOrderQuery query) {
        List<AdditionalOrder> list = additionalOrderDao.list(query);
        return list.size();
    }

    @Override
    public AdditionalOrder save(ProductOrder productOrder, AdditionalOrder additionalOrder) {

        additionalOrder.setEnabled(true);
        additionalOrder.setUser(productOrder.getUser());
        additionalOrder.setNo(OrderUtil.getOrderNo());
        additionalOrder.setState(0);//0待付款
        additionalOrder.setProductOrder(productOrder);
        additionalOrder=additionalOrderDao.save(additionalOrder);

        productOrder.setUpdateTime(new Date());
        productOrder.setAdditionalOrder(additionalOrder);
        productOrder.setStatements("等待用户补单");
        productOrder.setHandleState(9);//9等待用户补单
        productOrder=productOrderManager.save(productOrder);

        orderStepManager.save("等待用户补单", "等待用户补单", productOrder);//新增订单步骤
        notificationManager.save(additionalOrder.getUser(), Notification.Category.订单消息.toString(),"你有一个补单需要及时处理","客服为您提交了一个补单,请及时支付","","productOrder",productOrder.getId().toString());
        GetuiUtil.pushMessage(productOrder.getUser().getClientId(), "订单消息通知", "你有一个补单需要及时处理", "productOrder", productOrder.getId().toString());

        return additionalOrder;
    }

    @Override
    public synchronized void pay(Charge charge) {
        AdditionalOrderQuery additionalQuery = new AdditionalOrderQuery();
        additionalQuery.setNo(charge.getOrderNo().trim());
        additionalQuery.setState(0);
        AdditionalOrder order = check(additionalQuery);
        if (order != null) {

            order.setUpdateTime(new Date());
            order.setState(1);//已付款
            order.setCallback(charge.getId());
            order = additionalOrderDao.save(order);

            String remark="";//支付方式
            Money myMoney = moneyManager.mine(order.getUser());
            if(order.getPayment()==0){//0支付宝支付，1微信支付
                remark="支付宝支付";
            }else if(order.getPayment()==1){
                remark="微信支付";
            }else if(order.getPayment()==2){//余额支付
                remark = "余额支付";
                myMoney = moneyManager.frozen(myMoney, -order.getPrice());
            }

            //增加用户支出记录
            billManager.calc(order.getUser(), ShopDataVar.billCategory.用户.toString(), ShopDataVar.billType.消费支出.toString(), 0.0, order.getPrice(), myMoney.getBalance(), "additionalOrder", order.getNo(), remark, 1, null);

            productOrderManager.waitExecution(order.getProductOrder());//变为待施工状态

            //增加平台收入和记录
            Finance platFormFinance=financeManager.balance(order.getPrice());
            billManager.calc(null, ShopDataVar.billCategory.平台.toString(), ShopDataVar.billType.平台订单收入.toString(), order.getPrice(),0.0 , platFormFinance.getBalance(), "additionalOrder", order.getNo(), "", 1, null);


        }
    }



    @Override
    public AdditionalOrder cancel(AdditionalOrder additional) {
        additional.setUpdateTime(new Date());
        additional.setState(-1);
        additional = additionalOrderDao.save(additional);

//        if (additional.getPoint() != null && additional.getPoint() > 0) {//退还积分
//            pointManager.balance(additional.getUser(), additional.getPoint());
//            Point myPoint = pointManager.frozen(additional.getUser(), -additional.getPoint());
//            //point_record积分变动纪录
//            pointRecordManager.save(additional.getUser(), CommonVar.PointRecordType.退还积分.toString(), additional.getPoint().intValue(), 0, myPoint.getBalance().intValue(), "退还积分");
//        }

//        orderStepManager.save("订单已取消","订单已取消",additional);//新增订单步骤

        return additional;
    }

    @Override
    public List<AdditionalOrder> list(String hql, Object[] params) {
        return additionalOrderDao.list(hql, params);
    }

//    //    退款
//    public synchronized void refund(Refund refund) {
//        AdditionalOrderQuery additionalQuery = new AdditionalOrderQuery();
//        additionalQuery.setCallback(refund.getCharge().trim());
//        additionalQuery.setRefundState(2);
//        AdditionalOrder additional = check(additionalQuery);
//        if (additional != null) {
//            additional.setUpdateTime(new Date());
//            additional.setRefundState(1);//已退款
//            additional.setStatements("已退款");
//            additional.setState(-1);
//            additional = additionalOrderDao.save(additional);
//
//            //增加用户退款记录
//            billManager.calc(additional.getUser(), "用户", ShopDataVar.billType.消费退款.toString(), 0.0, additional.getPay(), 0.0, "order", additional.getNo(), null, 1, null);
//
//
//            //Finance 表 变化
//            Finance finance = financeManager.get(1);
//            financeManager.balance(-additional.getPrice());
//            //增加店铺 订单退款记录
////            billManager.calcShop(additional.getShop(), "店铺", CommonVar.BillType.订单退款.toString(), 0.0, additional.getPrice(), 0.0, "order", additional.getNo(), null, 1, null);
//
//            orderStepManager.save("订单已取消","订单已取消",additional);//新增订单步骤
//
//        }
//    }

//    @Override
//    public AdditionalOrder executeRefund(AdditionalOrder additional, Double refundPrice) {
//        //退款流程
//        Pingpp.apiKey = PingConfig.APIKEY;
//        Pingpp.setVerifySSL(Boolean.FALSE);
//
//        additional.setRefundAmount(StringUtil.toDecimal(refundPrice, 2));
//        additional = additionalOrderDao.save(additional);
//        if (StringUtils.isEmpty(additional.getCallback())) {
//            return additional;
//        }
//
//        try {
//            if (refundPrice > additional.getPay()) {
//                refundPrice = additional.getPay();
//            }
//
//            try {
//                //当前退款金额小于上一笔支付金额
//                Charge ch = Charge.retrieve(additional.getCallback());
//                Map<String, Object> refundMap = new HashMap<String, Object>();
//                refundMap.put("amount", (int) (StringUtil.toDecimal(refundPrice, 2) * 100));
//                refundMap.put("description", "订单退货退款");
//                Map<String, String> initialMetadata = new HashMap<String, String>();
//                initialMetadata.put("order_type", "additional");
//                refundMap.put("metadata", initialMetadata);
//                Refund re = ch.getRefunds().create(refundMap);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            additional.setUpdateTime(new Date());
//            additional.setRefundState(2);//退款中
//            additional.setStatements("退款中,请耐心等待");
//            additional.setRefundAmount(StringUtil.toDecimal(refundPrice, 2));
//            additional = additionalOrderDao.save(additional);
//
//            return additional;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


}